package com.markhsiu.store.disk;

import com.markhsiu.core.constant.Bits;

import io.openmessaging.demo.DefaultBytesMessage;
import io.openmessaging.demo.DefaultKeyValue;

public class MessageUtil {

	public static final String ID = "MessageId";
	
	/**
	 * len+header + len+properties + len+body
	 * 
	 * @param message
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static void buildBytes(final DefaultBytesMessage message, final  byte[] data, int offset) {
		String ID = message.getID();
		DefaultKeyValue headers = message.headers();
		DefaultKeyValue properties = message.properties();
		byte[] body = message.getBody();
		
		int IDLen =   ID.length();
		int headerLen = headers.size();
		int properyLen = properties.size();
		int bodyLen =   body.length;	
		
		Bits.putShort(data, offset, (short) IDLen);
		offset += 2;
		ID.getBytes(0, IDLen, data, offset);
		offset += IDLen;
		
		Bits.putShort(data, offset, (short) headerLen);
		offset += 2;
		if(headerLen > 0){
			headers.mapToBytes(data, offset);
			offset += headerLen;
		}
	
		
		Bits.putShort(data, offset,  (short) properyLen);
		offset += 2;
		properties.mapToBytes(data, offset);
		offset += properyLen;
		
		Bits.putShort(data, offset, (short) bodyLen);
		offset += 2;
		System.arraycopy(body, 0, data, offset, bodyLen);
		offset += bodyLen;
	}

	public static int restore(final byte[] data, int offset, final DefaultBytesMessage message) {
		message.clear();
		
		int oldOffset = offset;
		
		//MessageId
		int IDLen = byteToShort(data, offset);
		offset += 2;
		message.headers().put(ID, data, offset, IDLen);
		offset += IDLen;
		
		// headers
		int headerLen = byteToShort(data, offset);
		offset += 2;
		if(headerLen > 0 ){
			message.headers().bytesToMap(data, offset, headerLen);
			offset += headerLen;
		}	

		// propertis
		int properyLen = byteToShort(data, offset);
		offset += 2;
		message.properties().bytesToMap(data, offset, properyLen);
		offset += properyLen;

		// body
		int bodyLen = byteToShort(data, offset);
		offset += 2;
		byte[] body = new byte[bodyLen];
		System.arraycopy(data, offset, body, 0, bodyLen);
		message.setBody(body);
		offset += bodyLen;
		
		return offset - oldOffset;
	}

	public static short byteToShort(byte[] data, int offset) {
		return Bits.toShort(data[offset + 0], data[offset + 1]);
	}

	public static int byteToInt(byte[] data, int offset) {
		return Bits.toInt(data[offset + 0], data[offset + 1], data[offset + 2], data[offset + 3]);
	}

}